﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using YushengMall.Backend.Api.Entity;
using YushengMall.Backend.Api.ParamModel;

namespace YushengMall.Backend.Api.Common
{
    public class Authentication
    {
        private readonly TokenParameter _tokenParameter = new TokenParameter();
        public Authentication()
        {
            var config = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
            _tokenParameter = config.GetSection("TokenParameter").Get<TokenParameter>();
        }


        public string[] RequestToken(string name,string role)
        {



            // var claims = new[]{
            //     new Claim(ClaimTypes.Name,request.UserName),
            //     new Claim(ClaimTypes.Role,"")
            // };
            /// <summary>
            /// 生成token和RefreshToken
            /// </summary>
            /// <returns></returns>
            var token = GenUserToken(name,role);
            var refreshToken = "123456";
            return new[] { token, refreshToken };
        }

        private string GenUserToken(string UserName, string Role)
        {
            var claims = new[]{
                new Claim(ClaimTypes.Name,UserName),
                new Claim(ClaimTypes.Role,Role)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(_tokenParameter.Issuer, null, claims,
                expires: DateTime.UtcNow.AddMinutes(_tokenParameter.accessExpiration),
                signingCredentials: credentials);
            var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }

        public dynamic Refreshtoken([FromBody] RefreshTokenParameter request)
        {


            var handler = new JwtSecurityTokenHandler();

            try
            {
                ClaimsPrincipal claim = handler.ValidateToken(request.Token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_tokenParameter.Secret)),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                },
                out SecurityToken securityToken
                );
                var username = claim.Identity.Name;
                
                

                var Token = GenUserToken(username, "");
                var refreshtoken = "654321";
                return new[] { Token, refreshtoken };
            }
            catch (Exception)
            {
                return "Invalid Request";
            }

        }
    }
}
